package pe.com.itworth.ttsclient;

import java.util.Locale;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

import pe.com.itworth.ttsclient.controller.R;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class TTSPOP3Client extends Activity implements TextToSpeech.OnInitListener {
	
	private static final String TAG = "TextToSpeechDemo";

    private TextToSpeech mTts;
    private Button mAgainButton;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		
		
		// Initialize text-to-speech. This is an asynchronous operation.
        // The OnInitListener (second argument) is called after initialization completes.
        mTts = new TextToSpeech(this,
            this  // TextToSpeech.OnInitListener
            );

        // The button is disabled in the layout.
        // It will be enabled upon initialization of the TTS engine.
        mAgainButton = (Button) findViewById(R.id.again_button);

        mAgainButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                cargarMensajes();
                sayHello();
            }
        });
        
        cargarMensajes();
		
	}
	
	private void cargarMensajes() {
		Properties props = new Properties();

		String host = "pop.gmail.com";
		String username = "danielito.fisi@gmail.com";
		String password = "danielitofisi";
		String provider = "pop3s";

		try {

			// Connect to the POP3 server
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore(provider);
			store.connect(host, username, password);

			// Open the folder
			Folder inbox = store.getFolder("INBOX");
			if (inbox == null) {
				System.out.println("No INBOX");
				System.exit(1);
			}
			inbox.open(Folder.READ_ONLY);

			// Get the messages from the server
			Message[] messages = inbox.getMessages();
			for (int i = 0; i < messages.length; i++) {
				 mostrarAlerta(messages[i].getContent().toString());
				 HELLO = messages[i].getContent().toString();
			}
			
			if(HELLO == null || HELLO.equals("")) HELLO = "No hay mensajes";

			// Close the connection
			// but don't remove the messages from the server
			inbox.close(false);
			store.close();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void mostrarAlerta(String mensaje) {
		final Toast toast = Toast.makeText(TTSPOP3Client.this, mensaje,
				Toast.LENGTH_LONG);
		toast.show();
	}
	
	
	
	
	
	@Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }

        super.onDestroy();
    }

    // Implements TextToSpeech.OnInitListener.
    public void onInit(int status) {
        // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
        if (status == TextToSpeech.SUCCESS) {
            // Set preferred language to US english.
            // Note that a language may not be available, and the result will indicate this.
            int result = mTts.setLanguage(Locale.US);
            // Try this someday for some interesting results.
            // int result mTts.setLanguage(Locale.FRANCE);
            if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
               // Lanuage data is missing or the language is not supported.
                Log.e(TAG, "Language is not available.");
            } else {
                // Check the documentation for other possible result codes.
                // For example, the language may be available for the locale,
                // but not for the specified country and variant.

                // The TTS engine has been successfully initialized.
                // Allow the user to press the button for the app to speak again.
                mAgainButton.setEnabled(true);
                // Greet the user.
                sayHello();
            }
        } else {
            // Initialization failed.
            Log.e(TAG, "Could not initialize TextToSpeech.");
        }
    }

    private static String HELLO = "No hay mensajes";

    private void sayHello() {
        // Select a random hello.
        mTts.speak(HELLO,
            TextToSpeech.QUEUE_FLUSH,  // Drop all pending entries in the playback queue.
            null);
    }
}